#!/bin/bash

#Backup your MySQL database and have it mailed to you
#requires mutt or another command line email client

if [ -z "$1" ]
then
    echo "Database name expected as the first parameter"
    exit
fi

if [ -z "$2" ]
then
    echo "Recipient expected as second parameter"
    exit;
fi

if [ -z "$3" ]
then
        echo "Usuario esperado como tercer parametro"
        exit;
fi

if [ -z "$4" ]
then
        echo "Contrasenia esperada como cuarto parametro"
        exit;
fi

# config
tmp="/tmp"
db_user=$3
db_pw=$4
db_name=$1
db_host="localhost"
recp=$2
today=`date +%Y-%m-%d`
mysqldump_opts="--add-drop-table -acQq"
# email settings
subject="DB Backup for $1"
#sql_file=$tmp/$db_name.$today.sql
sql_file=$db_name.$today.sql
#gzip_file=$tmp/$db_name.$today.sql.gz
gzip_file=$db_name.$today.sql.gz
filepiece=dbbackup
# create the backup
mysqldump $mysqldump_opts -u $db_user -h $db_host -p$db_pw $db_name > $sql_file

#create the gzip'd attachment
gzip $sql_file

#split the gzip into 8M size files
split -b 8m $gzip_file $filepiece

#send the mail
#we could also scp it offsite instead (better)
for file in $filepiece*; do
echo "Automated database backup" | mutt -a $file -s "$subject" $recp
done

#delete temp file
rm $gzip_file

#Eliminar las partes
for file in $filepiece*; do
rm $file
done